package com.jnetx.javax.sip.message;

import com.jnetx.javax.sip.header.HeaderParser;
import com.jnetx.javax.sip.util.ByteArrayUtil;
import com.jnetx.javax.sip.util.ByteData;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.sip.header.Header;
import java.text.ParseException;

/**
 * Created by IntelliJ IDEA.
 * User: deps
 * Date: 29.03.11
 * Time: 18:41
 * To change this template use File | Settings | File Templates.
 */
public class SIPResponseParser extends SIPMessageParser {
    private final static Log log = LogFactory.getLog(SIPResponseParser.class);

    public static SIPResponse parseResponse(byte[] messageData) throws ParseException {
        SIPResponse response = new SIPResponse();
        final int sipVersionStart = ByteArrayUtil.firstMissing(messageData, ' ');
        final int sipVersionEnd = ByteArrayUtil.firstOccurence(messageData, ' ', sipVersionStart);
        response.setSIPVersion(new String(messageData, sipVersionStart, sipVersionEnd));
        final int responseCodeStart = ByteArrayUtil.firstMissing(messageData, ' ', sipVersionEnd + 1);
        final int responseCodeEnd = ByteArrayUtil.firstOccurence(messageData, ' ', responseCodeStart + 1);
        response.setStatusCode(Integer.parseInt(new String(messageData, responseCodeStart, responseCodeEnd - responseCodeStart)));
        final int responsePhraseStart = ByteArrayUtil.firstMissing(messageData, ' ', responseCodeEnd + 1);
        final int responsePhraseEnd = ByteArrayUtil.firstEndOfLine(messageData, responsePhraseStart);
        response.setReasonPhrase(new String(messageData, responsePhraseStart, responsePhraseEnd - responsePhraseStart));
        //Parse headers
        final int startOfHeaders = responsePhraseEnd + 2;
        final int startOfBody = parseHeaders(messageData, response, startOfHeaders);
        //Parse body
        //todo
        return response;
    }
}
